const dbHandler = require("../../pipe/dbhandler");
const sipUtils = require("../../utils/sipUtils");
const constants = require("../../data/constants");
const log4js = require('../../data/log');
const logger = log4js.getLogger('sip');

/**
 * 生成 invite 请求信令
 */
module.exports={

    invite: async function (media_ip, deviceid, channel, udpPort) {
        if (!deviceid) {
            logger.warn('计算invite时，设备id异常,deviceid', deviceid, 'channel', channel);
            return null;
        }
        let ssrc = `${deviceid.substring(13)}${channel.substring(17)}`;
        const deviceInfo = await dbHandler.loadDevice(deviceid);

        let res;
        if (!deviceInfo || !deviceInfo.channels) {
            logger.warn('计算invite时，设备未注册,deviceid', deviceid, 'channel', channel, 'deviceInfo', deviceInfo);
            res = null;
        }else {
            let channelInfo = deviceInfo.channels[channel];

            if (!channelInfo) {
                logger.error(`计算invite时，设备 ${deviceid} 中没有找到 channel : ${channel}`, 'deviceInfo', deviceInfo);
                res = null;
            } else {
                let content = 'v=0\r\n' +
                    `o=${channel} 0 0 IN IP4 ${media_ip}\r\n` +
                    's=Play\r\n' +
                    `c=IN IP4 ${media_ip}\r\n` +
                    't=0 0\r\n' +
                    `m=video ${udpPort} TCP/RTP/AVP 96 97 98\r\n` +
                    'a=setup:passive\r\n' +
                    'a=rtpmap:96 PS/90000\r\n' +
                    'a=rtpmap:97 MPEG4/90000\r\n' +
                    'a=rtpmap:98 H264/90000\r\n' +
                    'a=recvonly\r\n' +
                    'a=streamprofile:0\r\n' +
                    'a=streamnumber:0\r\n' +
                    `y=${ssrc}\r\n\r\n`
                ;

                let cseq = {method: 'INVITE', seq: 1};
                let callId = Math.round((new Date()).getTime() / 1000) + '';

                let via = sipUtils.generateVia(channelInfo.protocol, deviceInfo.via_params);
                res = {
                    method: cseq.method, content,
                    uri: sipUtils.generateUri(channelInfo.deviceid, channel, null, deviceInfo.sip_command_host, deviceInfo.sip_command_port),
                    version: constants.sip.version,
                    headers: {
                        via, cseq,
                        from: {
                            uri: `sip:${constants.sip.option.sip_command_account}@${constants.sip.option.server_realm}`,
                            params: {tag: 'live'}
                        },
                        to: {uri: `sip:${channel}@${constants.sip.option.server_realm}`},
                        'call-id': callId,
                        'Content-Type': 'Application/SDP',
                        'expires': '3600',
                        'Max-Forwards': 70,
                        'User-Agent': constants.sip.useragent,
                        contact: sipUtils.generateContact(),
                        subject: `${channel}:0,${constants.sip.option.sip_command_account}:0`
                    }
                };
                channelInfo.invite = res;
                channelInfo.invite_port = udpPort;
                constants.registry.invites[callId] = {deviceid, channel};
            }
        }
        return res;
    },
}
